<template>
	<view class="auth">
		<view class="title">ugo-登录</view>
		<button class="loginBtnAvatar" open-type="chooseAvatar" @chooseavatar="getAvatar">
			<image class="avatar" :src="avatarUrl"></image>
		</button>
		
		<view>
			<input type="nickname" placeholder="点击修改昵称" v-model="nickName"/>
		</view>
		<button class="loginBtn" size="mini"  @click="hLogin" type="primary">
			登录
		</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				avatarUrl: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
				nickName: ''
			}
		},
		onShow() {
			const userInfo = uni.getStorageSync('userInfo') || {}
			this.avatarUrl = userInfo.avatarUrl
			this.nickName = userInfo.nickName
		},
		async onLoad() {
			const res = await uni.login()
			console.log(res)
			this.code = res.code
		},
		methods: {
			getAvatar(e){
				console.log(e)
				this.avatarUrl = e.detail.avatarUrl
			},
			// 调用接口登录
			async hLogin(user) {
				// 登录所需参数
				const res = await uni.getUserProfile({
					desc: '获取微信用户信息'
				});
				console.log(res)
				const {
					encryptedData,
					iv,
					rawData,
					signature
				} = res
				
				const {data} = await this.request({
					url: "/users/wxlogin",
					method: "post",
					data: {
						encryptedData,
						iv,
						rawData,
						signature,
						code: this.code
					}
				});
				console.log(data);
        // 保存token
				uni.setStorageSync("token", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjQwNSwiaWF0IjoxNjg3NTkyNjM3LCJleHAiOjEwMDE2ODc1OTI2MzZ9.yZ9K3qdLKtdJHBi2bMXNGdm71BQ0V-VGUhQm7GzND_U"
)
        // 保存用户更新后的头像和昵称 -- 只是纯前端处理，服务器中并没有对应的接口来保存修改结果
				uni.setStorageSync("userInfo", {avatarUrl: this.avatarUrl, nickName: this.nickName})
				// 后退
				uni.navigateBack()
			}
		}
	}
</script>
<style lang="scss">
.auth {
	
	padding:50rpx;
	text-align: center;
	.title{
		margin: 40rpx auto;
	}
	.loginBtnAvatar {
		width: 200rpx;
		height: 200rpx;
		border-radius: 50%;
		padding:0px;
		margin: 40rpx auto;
	}
	.avatar {
		width: 200rpx;
		height: 200rpx;
		border-radius: 50%;
		border: 2rpx solid #fff;
	}

	.nickname {
		display: block;
		text-align: center;
		margin-top: 20rpx;
		font-size: 30rpx;
		color: #fff;
	}
	.loginBtn {
		width: 200rpx;
		margin: 50rpx auto;
		display: block;
	}
}
</style>